#!/usr/bin/python
# -*- coding: UTF-8 -*-
from docx import Document
import os
import re
from write.AbstractWrite import AbstractWrite
from util import Util


class ShipEvaluation(AbstractWrite):
	def __init__(self):
		super().__init__()

	def setDic(self, cargoTextDic, cargoUnderlineDic, shipTextDic, shipUnderlineDic):
		self.cargoTextDic = cargoTextDic
		self.cargoUnderlineDic = cargoUnderlineDic
		self.shipTextDic = shipTextDic
		self.shipUnderlineDic = shipUnderlineDic

	def write(self):
		oldPath, newPath = self._getPath("成交评估说明表")
		doc = Document(oldPath)
		table = doc.tables[0]

		# 修改船名
		# #保留格式改文字
		runs = table.cell(0, 1).paragraphs[0].runs
		[run.clear() for run in runs[1:]]
		runs[0].text = str("船    名：" + self.shipUnderlineDic["航次"][0])

		# 修改航次
		runs = table.cell(0, 2).paragraphs[0].runs
		[run.clear() for run in runs[1:]]
		runs[0].text = str("航    次：" + self.shipUnderlineDic["航次"][1])

		# 修改客户名
		runs = table.cell(2, 1).paragraphs[0].runs
		[run.clear() for run in runs[1:]]
		runs[0].text = str(self.shipTextDic["乙方"])

		# 修改航线：
		run = Util.getRun(table.cell(3, 1).paragraphs, "航线：")
		run.text = run.text.replace('航线：', '航线：{load}-{discharge}'.format(
			load=self.shipUnderlineDic["装货港"][0],
			discharge=self.shipUnderlineDic["卸货港"][0]))
		# 修改受载期
		run = Util.getRun(table.cell(3, 1).paragraphs, "受载期：")
		run.text = run.text.replace('受载期：', '受载期：' + self.shipTextDic["受载期"].replace(" ", ""))

		# 修改装卸天
		run = Util.getRun(table.cell(3, 1).paragraphs, "装卸天：")
		try:
			temp = re.findall(r"-?\d+\.?\d*e?-?\d*?", self.shipTextDic["允许装卸时间"])[0]
			run.text = run.text.replace('装卸天：', '装卸天：装卸两港合并' + temp + '天')
		except Exception as e:
			print("!!!非格式化装卸天!!!:" + str(e))

		# 修改运价
		if "基本运价" in self.shipUnderlineDic.keys():
			run = Util.getRun(table.cell(4, 1).paragraphs, "货主运价：")
			run.text = run.text.replace('货主运价：', '货主运价：人民币{Price}元/吨'
			                            .format(Price=self.cargoUnderlineDic["基本运价"][0]))
			run = Util.getRun(table.cell(4, 1).paragraphs, "租船运价：")
			run.text = run.text.replace('租船运价：', '租船运价：人民币{Price}元/吨'
			                            .format(Price=self.shipUnderlineDic["基本运价"][0]))
			run = Util.getRun(table.cell(4, 1).paragraphs, "收益：")
			tonProfit = float(self.cargoUnderlineDic["基本运价"][0]) - float(self.shipUnderlineDic["基本运价"][0])
			tonProfit = round(tonProfit, 2)
			profit = tonProfit * float(self.shipUnderlineDic["货量"][0])
			profit = round(profit, 2) / 10000.0
			run.text = run.text.replace('收益：', '收益：预计{Profit}万元（即我公司赚取运价差每吨{TonProfit}元）'
			                            .format(Profit=profit, TonProfit=tonProfit))
		else:
			run = Util.getRun(table.cell(4, 1).paragraphs, "收益：")
			run.text = run.text.replace('收益：', '收益：预计  万元（即我公司赚取运价差每吨  元）')


		# 修改货量
		run = Util.getRun(table.cell(11, 1).paragraphs, "货量：")
		run.text = run.text.replace('货量：', '货量：{cargoVolume}/{cargoType}'.format(
			cargoVolume=self.shipTextDic["货量"].split("，")[0].replace(" ", ""),
			cargoType=self.shipUnderlineDic["货种"][0]))

		# 修改滞期费率
		if "滞速费率" not in self.shipUnderlineDic.keys() or len(self.shipUnderlineDic["滞速费率"]) == 0:
			if (float(self.shipUnderlineDic["指数滞速费"][1][1]) / 100) > 1:
				indexText = "按{index}确认（单位：元/天）：".format(index=self.shipUnderlineDic["指数滞速费"][0][0])
			else:
				indexText = "按{index}确认（单位：元/吨*天）：".format(index=self.shipUnderlineDic["指数滞速费"][0][0])

			for i in range(1, len(self.shipUnderlineDic["指数滞速费"])):
				if len(self.shipUnderlineDic["指数滞速费"][0]) == 2:
					indexText += "{First},{Second}；".format(First=self.shipUnderlineDic["指数滞速费"][i][0],
					                                        Second=self.shipUnderlineDic["指数滞速费"][i][1])
				else:
					indexText += "{First},{Second}/{Third}；".format(First=self.shipUnderlineDic["指数滞速费"][i][0],
					                                                Second=self.shipUnderlineDic["指数滞速费"][i][1],
					                                                Third=self.shipUnderlineDic["指数滞速费"][i][2])
			run = Util.getRun(table.cell(11, 1).paragraphs, "费率：")
			run.text = run.text.replace('费率：', '费率：{Text}。'.format(Text=indexText))

		else:
			run = Util.getRun(table.cell(11, 1).paragraphs, "费率：")
			run.text = run.text.replace('费率：', '费率：{Text}。'.format(Text=self.shipTextDic["滞速费率"].split("。")[0]))

		# 修改付款条约
		run = Util.getRun(table.cell(11, 1).paragraphs, "付款：")
		run.text = run.text.replace('付款：', '付款：' + self.shipTextDic["航次运费付款"])

		# 修改日期
		run = Util.getRun(table.cell(1, 1).paragraphs, "合同日期：")
		run.text = run.text.replace('合同日期：', '合同日期：' + self.shipTextDic["签约日期"])
		run = Util.getRun(table.cell(12, 2).paragraphs, "日期：")
		run.text = run.text.replace('日期：', '日期：' + self.shipTextDic["签约日期"])

		doc.save(newPath)

	def _getPath(self, modelName):
		oldName = ""
		outputPath = os.path.join(self.outputDir,
		                          "{shipName}V{voyage}".format(shipName=self.shipUnderlineDic["航次"][0],
		                                                       voyage=self.shipUnderlineDic["航次"][1]))
		if not os.path.exists(outputPath):
			os.makedirs(outputPath)
		files = os.listdir(self.modelPath)
		files.sort()

		for file in files:
			if os.path.splitext(file)[0] == modelName:
				oldName = file
		newname = "船附件2：{shipName}V{voyage}{oldName}".format(shipName=self.shipUnderlineDic["航次"][0],
		                                                        voyage=self.shipUnderlineDic["航次"][1],
		                                                        oldName=oldName)
		newPath = os.path.join(outputPath, newname)
		oldPath = os.path.join(self.modelPath, oldName)
		return oldPath, newPath
